package com.woniu.utils;

import com.woniu.entity.User;
import com.woniu.mapper.UserMapper;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
@Slf4j
public class MinioUtil {
    @Resource
    private UserMapper userMapper;
    @Resource
    private MinioClient minioClient;
    public Map<String,Object> updateFile(MultipartFile file,String bucketName) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        //1.判断文件是否为空
        if (file.isEmpty() || file.getSize() == 0) {
            map.put("code", 500);
            map.put("msg", "文件不能为空");
            return map;
        }
        //2.判断桶
        boolean flag = minioClient.bucketExists(bucketName);
        if (!flag) {
            //创建桶
            minioClient.makeBucket(bucketName);
        }
        //3.文件上传 上传之前 1.文件名会不会重复 2.文件格式问题
        //通过文件名 获得后缀 判断文件类型
        String originalFilename = file.getOriginalFilename();
        //字符串的subString字符串截取
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //文件名怎么保证唯一 UUID 命名 桶名+时间/UUID+suffix
        String filename = bucketName+"_"+System.currentTimeMillis()+"/"+ UUID.randomUUID()+suffix;
        //上传文件
        InputStream inputStream = file.getInputStream();
        PutObjectOptions putObjectOptions = new PutObjectOptions(inputStream.available(), -1);
        minioClient.putObject(bucketName,filename,inputStream,putObjectOptions);
        log.info("上传成功");
        String url = minioClient.getObjectUrl(bucketName, filename);
        map.put("code",200);
        map.put("msg","文件上传成功");
        map.put("url",url);

        User user = new User();
        User user1 = userMapper.findById(user.getId());
        String originalFilename1 = file.getOriginalFilename();
        String suffix1 = originalFilename.substring(originalFilename1.lastIndexOf("buckName"));
        user1.setImgUrl(suffix1);
        return map;
    }

}
